// frontend/js/order.js
new Vue({
    el: '#app',
    data: {
        cartItems: [],
        order: {
            customerName: '',
            note: '',
            orderDetails: []
        },
        submitting: false
    },
    computed: {
        // 是否可以提交
        canSubmit() {
            return this.order.customerName.trim() && 
                   this.cartItems.length > 0 && 
                   !this.submitting;
        }
    },
    mounted() {
        this.restoreCart();
        // 自动填充常用名字
        this.autoFillCustomerName();
    },
    methods: {
        // 从本地存储恢复购物车
        restoreCart() {
            try {
                const savedCart = localStorage.getItem('dishes_cart');
                if (savedCart) {
                    this.cartItems = JSON.parse(savedCart);
                    // 转换为订单详情格式
                    this.order.orderDetails = this.cartItems.map(item => ({
                        productId: item.id,
                        quantity: item.quantity,
                        productName: item.name
                    }));
                }
            } catch (error) {
                console.error('恢复购物车失败:', error);
                this.cartItems = [];
            }
        },
        
        // 自动填充客户姓名（从URL参数或常用名）
        autoFillCustomerName() {
            const urlParams = new URLSearchParams(window.location.search);
            const nameFromUrl = urlParams.get('name');
            
            if (nameFromUrl) {
                this.order.customerName = nameFromUrl;
            } else {
                // 设置默认常用名
                this.order.customerName = '宝贝';
            }
        },
        
        // 返回上一页
        goBack() {
            window.history.back();
        },
        
        // 提交订单
        async submitOrder() {
            if (!this.canSubmit) return;
            
            this.submitting = true;
            const loading = showLoading('提交订单中...');
            
            try {
                // 验证数据
                if (!this.order.customerName.trim()) {
                    throw new Error('请输入你的名字');
                }
                
                if (this.order.orderDetails.length === 0) {
                    throw new Error('请选择餐品');
                }
                
                // 提交订单
                const result = await API.order.create(this.order);
                
                // 清空购物车
                localStorage.removeItem('dishes_cart');
                
                // 显示成功消息
                showSuccess('订单提交成功！我们会尽快处理');
                
                // 延迟跳转，让用户看到成功消息
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 2000);
                
            } catch (error) {
                handleApiError(error, '订单提交失败');
            } finally {
                this.submitting = false;
                hideLoading(loading);
            }
        }
    }
});